package src.leetcode.hot.mid_0005;

/**
 * @author liyizzz
 * @description 最长回文子串
 * @date 2024/12/19 17:06
 */
public class longestPalindrome {
    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.longestPalindrome("tattarrattat"));
    }
}

class Solution {
    int n;
    public String longestPalindrome(String s) {
        n = s.length();
        int left = 0, right = 1;
        for (int i = 0; i < n; i++) {
            // aba
            int length1 = expandAroundCenter(s, i, i);
            // abba
            int length2 = expandAroundCenter(s, i, i + 1);
            if (length1 * 2 - 1 > right - left) {
                left = i - length1 + 1;
                right = i + length1;
            }
            if (length2 * 2 > right - left) {
                left = i - length2 + 1;
                right = i + length2 + 1;
            }
        }
        return s.substring(left, right);
    }

    private int expandAroundCenter(String s, int left, int right) {
        int count = 0;
        while (left >= 0 && right < n) {
            if (s.charAt(left) != s.charAt(right)) return count;
            count++;
            left--;
            right++;
        }
        return count;
    }
}